package interview;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

class MyResource {
    ReentrantLock lock = new ReentrantLock();
    Condition con1 = lock.newCondition();
    Condition con2 = lock.newCondition();

    int state = 1;
    int num = 1;

    public void printOdd() {
        lock.lock();
        try {
            while (state != 1) {
                con1.await();
            }

            System.out.println(Thread.currentThread().getName() + "\t print "
                    + num);
            num++;
            state = 0;
            con2.signal();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printEven() {
        lock.lock();
        try {
            while (state != 0) {
                con2.await();
            }

            System.out.println(Thread.currentThread().getName() + "\t print "
                    + num);
            num++;
            state = 1;
            con1.signal();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

public class TakeTurnPrint1To100 {
    public static void main(String[] args) {
        MyResource rs = new MyResource();
        new Thread(()->{
            for (int i = 0; i < 50; i++) {
                rs.printOdd();
            }
        }, "A").start();

        new Thread(()->{
            for (int i = 0; i < 50; i++) {
                rs.printEven();
            }
        }, "B").start();
    }
}
